﻿using System;
using System.Net;
using System.Threading.Tasks;

namespace Task包装器
{
    class Program
    {
        static void Main(string[] args)
        {
            var task = GetTask("https://www.cnblogs.com/");
            Console.WriteLine(task.Result);


            Console.Read();
        }



        public static Task<string> GetTask(string url)
        { 
            WebClient client = new WebClient(); 
            TaskCompletionSource<string> source=new TaskCompletionSource<string>();

            // 内部源码 也是用TaskCompletionSource 实现的 
            //client.DownloadDataAsync(new Uri(""));

            client.DownloadDataCompleted += (sender, e) =>
            {
                try
                {
                    source.TrySetResult(System.Text.Encoding.UTF8.GetString(e.Result));
                }
                catch ( Exception ex)
                {
                    source.TrySetException(ex);
                }
            };
            client.DownloadDataAsync(new Uri(url));
            return source.Task; 
        }

    }
}
